package cn.mvc.web.service;

import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import org.fast.ioc.annotation.Inject;
import org.fast.ioc.annotation.Service;
import org.fast.web.Pager;

import cn.mvc.exception.ServiceException;
import cn.mvc.model.Category;
import cn.mvc.model.Content;
import cn.mvc.model.http.ContentModel;
import cn.mvc.web.dao.WebDao;

@Service("cntService")
public class ContentService {

	@Inject
	private WebDao webDao;

	public WebDao getWebDao() {
		return webDao;
	}

	public void setWebDao(WebDao webDao) {
		this.webDao = webDao;
	}

	/**
	 * 添加内容
	 * 
	 * @param cnt
	 * @return
	 * @throws ServiceException
	 */
	public int addContent(Content cnt) throws ServiceException {
		int r = 0;
		try {
			r = webDao.save("sql.content.update.add", cnt);
		} catch (SQLException e) {
			throw new ServiceException(e.getMessage());
		}
		return r;

	}

	public int totalContent() throws ServiceException {
		int count = 0;
		try {
			count = webDao.count("sql.content.query.count");
		} catch (SQLException e) {
			throw new ServiceException(e.getMessage());
		}
		return count;
	}

	/**
	 * 删除内容
	 * 
	 * @param id
	 * @return
	 * @throws ServiceException
	 */
	public int delContent(String id) throws ServiceException {
		int r = 0;
		try {
			r = webDao.delete("sql.content.update.del", id);
		} catch (SQLException e) {
			throw new ServiceException(e.getMessage());
		}
		return r;
	}

	/**
	 * 获取内容列表
	 * 
	 * @param pager
	 * @return
	 * @throws ServiceException
	 */
	public List<ContentModel> showContent(Pager pager) throws ServiceException {
		List<ContentModel> list = new ArrayList<ContentModel>();
		try {
			String sql = "SELECT cnt.id, cnt.title, CASE WHEN ISNULL(cate.name) THEN '默认分类' ELSE cate.name END AS category, cnt.note FROM mini_content cnt LEFT JOIN mini_category cate ON cnt.cid = cate.id ORDER BY cnt.id DESC";
			// mysql 分页 limt
			sql = sql + " limit " + pager.getStartRow() + ","
					+ pager.getPageSize();
			list = webDao.query(ContentModel.class, sql);

		} catch (SQLException e) {
			throw new ServiceException(e.getMessage());
		}
		return list;
	}

	public List<Category> getCategory() throws ServiceException {
		List<Category> list = new ArrayList<Category>();
		try {
			list = webDao.list(Category.class, "sql.category.query.list");
		} catch (SQLException e) {
			throw new ServiceException(e.getMessage());
		}
		return list;
	}
}
